#!/bin/bash

SWNAME=chrome
SWVER=${tmp_version}

DEB_PATH1=./downloads/${SWNAME}-ffmpeg-extra.deb
DEB_PATH2=./downloads/${SWNAME}-chromium.deb
DEB_PATH3=./downloads/${SWNAME}-l10n.deb

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	:
}

function sw_install() {
	apt-get install -y --allow-downgrades chromium chromium-l10n
	exit_if_fail $? "安装失败"
}

function sw_create_desktop_file() {

	# 默认启动图标，没启用 --no-sandbox 删掉!
	rm -rf ${DIR_DESKTOP_FILES}/chromium.desktop

	STARTUP_SCRIPT_FILE=/usr/bin/${SWNAME}
	cat <<- EOF > ${STARTUP_SCRIPT_FILE}
		#!/bin/bash

		# enable virgl
		# GALLIUM_DRIVER=virpipe MESA_GL_VERSION_OVERRIDE=4.0 exec /usr/bin/chromium --no-sandbox "\$@"

		# --gtk-version=2 

		exec /usr/bin/chromium --no-sandbox --no-first-run --test-type --disable-infobars "\$@"
	EOF
	chmod a+x ${STARTUP_SCRIPT_FILE}

	cat <<- EOF > ${DSK_PATH}
		[Desktop Entry]
		Version=1.0
		Name=Chrome
		Exec=${SWNAME} %U
		Terminal=false
		X-MultipleArgs=false
		Type=Application
		Icon=chromium
		Categories=Network;WebBrowser;
		MimeType=text/html;text/xml;application/xhtml_xml;application/x-mimearchive;x-scheme-handler/http;x-scheme-handler/https;
		StartupWMClass=chromium
		StartupNotify=true
		Keywords=browser
	EOF
	cp2desktop ${DSK_PATH}

	# update-alternatives --display x-www-browser
	# update-alternatives --config x-www-browser
	# ls -l /usr/bin/x-www-browser
	# ln -sf /usr/bin/chrome /etc/alternatives/x-www-browser
	# xdg-settings get default-web-browser

	# 用于命令行下 open https://www.***.com
	sudo update-alternatives --remove x-www-browser /usr/bin/${SWNAME}
	sudo update-alternatives --install /usr/bin/x-www-browser x-www-browser /usr/bin/${SWNAME} 210
	sudo update-alternatives --set x-www-browser /usr/bin/${SWNAME}
	sudo ln -sf /usr/bin/${SWNAME} /etc/alternatives/x-www-browser

	# 这个可以让chrome不再显示“不是您的默认浏览器”
	sudo -u ${ZZ_USER_NAME} xdg-settings set default-web-browser ${DSK_FILE}

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center &       # 一定要是单引号

	if [ -f ./scripts/res/chrome.pref/Bookmarks ]; then
		sudo -u ${ZZ_USER_NAME} mkdir -p ${ZZ_USER_HOME}/.config/chromium/Default
		sudo -u ${ZZ_USER_NAME} cp -f ./scripts/res/chrome.pref/Bookmarks ${ZZ_USER_HOME}/.config/chromium/Default/Bookmarks
	fi

	if [ -f ./scripts/res/chrome.pref/Preferences ]; then
		sudo -u ${ZZ_USER_NAME} mkdir -p ${ZZ_USER_HOME}/.config/chromium/Default
		sudo -u ${ZZ_USER_NAME} cp -f ./scripts/res/chrome.pref/Preferences ${ZZ_USER_HOME}/.config/chromium/Default/Preferences
	fi

}

if [ "${action}" == "卸载" ]; then
	apt-get remove chromium chromium-l10n
	rm2desktop ${DSK_FILE}
else
	sw_download
	sw_install
	sw_create_desktop_file
fi
